package upm.pb4agent.team5.custom;

import jade.core.AID;
import jade.core.behaviours.SimpleBehaviour;
import jade.lang.acl.ACLMessage;
import upm.pb4agent.ontology.Registration;
import upm.pb4agent.ontology.RegistrationForm;
import upm.pb4agent.team5.common.RegistrationDesk;

public class BManagerRequestInscription extends SimpleBehaviour {
	private static final long serialVersionUID = -8951917520548839211L;
	private static final int WAIT_PER_SEARCH = 100; // Milliseconds
	
	private Manager manager = null;
	private RegistrationForm registrationForm = null;
	private boolean done = false;

	public BManagerRequestInscription(Manager manager, RegistrationForm registrationForm) {
		this.manager = manager;
		this.registrationForm = registrationForm;
	}
	
	public void action()
	{   
		try {
			AID aid = manager.findAID(RegistrationDesk.DF_NAME);
			
			// Get first occurrence
			if (aid != null) {
				// Preparing action
				Registration registration = new Registration();
				registration.setRegistrationForm(registrationForm);
				
				// Sending request
				System.out.println(manager.getLocalName() + ": Requests team inscription to " + RegistrationDesk.DF_NAME);		
				manager.send(registration, aid, ACLMessage.REQUEST);
				
				// Getting request
				ACLMessage msg = manager.blockingReceive();
				if (msg.getPerformative() == ACLMessage.INFORM) 
					System.out.println(manager.getLocalName() + ": Team registration successfully completed");
				else  		
					System.out.println(manager.getLocalName() + ": Team registration failed");
				
				// Setting done flag for finish
				done = true;
			}
			
			manager.doWait(WAIT_PER_SEARCH);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean done() {
		return done;
	}
	
}
